import "reflect-metadata"
import fs from "fs"
import path from "path"
import Router from "koa-router"
import { BASE_PATH_MAP, ROUTER_MAP } from './constant'
import { RouteMeta, PathMeta } from './type'

export const addRouter = (router: Router) => {
  const ctrPath = path.join(__dirname, "controller")
  const modules: ObjectConstructor[] = []

  // 扫描 controller 文件夹，收集所有 controller
  fs.readdirSync(ctrPath).forEach(name => {
    if (/^[^.]+\.(t|j)s$/.test(name)) {
      modules.push(require(path.join(ctrPath, name)).default)
    }
  })

  // 结合 meta 数据添加路由和验证
  modules.forEach(m => {
    const routerMap: RouteMeta[] = Reflect.getMetadata(ROUTER_MAP, m, 'method') || []
    const basePathMap: PathMeta[] = Reflect.getMetadata(BASE_PATH_MAP, m) || []
    const basePath: PathMeta = basePathMap.pop()
    if (routerMap.length) {
      const ctr = new m()
      routerMap.forEach(route => {
        const { name, method, path } = route
        const newPath: string = basePath ? (basePath.path + path) : path
        console.log('newPath :>> ', newPath);
        // @ts-ignore
        router[method](newPath, ctr[name])
      })
    }
  })
}
